<?php
/**
 * DummyService.php
 * 文件描述 虚拟对象逻辑页
 * Created on 2020/8/31 18:35
 * Created by 刘小龙 595929049@qq.com
 */

namespace app\xiangji\services;



use app\common\caches\DummyCache;
use app\common\facades\auth\Auth;
use app\Request;
use app\common\helpers\Response;
use app\common\models\Dummy;
use app\xiangji\exception\BadRequestException;
use app\xiangji\exception\ModelNotFoundException;

class DummyService
{
    private $dummyModel;
    private $user;

    public function __construct(Dummy $dummyModel)
    {
        $this->user = Auth::guard('api')->user();
        $this->dummyModel = $dummyModel;
    }

    /**
     * @todo 获取虚拟对象信息
     * @return mixed|null
     */
    public function show()
    {
        $dummy = $this->user->dummy()->with('score')->find();
        return $dummy;
    }

    /**
     * @todo 创建虚拟对象
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request)
    {
        // 已经创建虚拟对象则不能再创建
        if ($this->user->dummy){
            throw new BadRequestException('已存在虚拟对象，不可再次创建', Response::HTTP_FORBIDDEN);
        }
        $data = $request->post([
            'avatar',
            'name',
            'sex',
            'age',
            'birthday',
            'height',
            'weight',
            'horoscope',
            'labels'
        ]);
        // 通过关联保存虚拟对象到用户
        return $this->user->dummy()->save($data);
    }

    public function update(Request $request)
    {
        // 不存在虚拟对象则不能更新，应提醒用户创建
        if (!$this->user->dummy){
            throw new ModelNotFoundException('不存在虚拟对象，请先创建创建');
        }
        $data = $request->put([
            'avatar',
            'name',
            'sex',
            'age',
            'birthday',
            'height',
            'weight',
            'horoscope',
            'labels'
        ]);
        // 通过关联保存虚拟对象到用户
        return $this->user->dummy->save($data);
    }
}
